/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.minierp.validator;

import com.minierp.bean.DepartmentBean;
import com.minierp.dao.DepartmentDao;
import com.minierp.model.Department;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class DepartmentValidator implements Validator {
	private DepartmentDao departmentDao;

	public boolean supports(Class clazz) {
		return DepartmentBean.class.isAssignableFrom(clazz);
	}

	public void validate(Object obj, Errors errors) {
		DepartmentBean form = (DepartmentBean) obj;
		boolean hasError = false;
		Department d;
		if (form.getCodeRule().getGenerateRule().equals("MANUAL")
				|| form.getDepartment().getId() != 0L) {
			if (form.getDepartment().getDepartmentCode() != null
					&& !form.getDepartment().getDepartmentCode().trim()
							.equals("")) {
				d = this.departmentDao.get(form.getDepartment()
						.getDepartmentCode());
				if (d != null && d.getId() != form.getDepartment().getId()) {
					errors.rejectValue("department.departmentCode", "",
							"『编号』已经存在");
					hasError = true;
				}
			} else {
				errors.rejectValue("department.departmentCode", "", "请输入『编号』");
				hasError = true;
			}
		}

		if (!hasError) {
			if (form.getDepartment().getDepartmentName() != null
					&& !form.getDepartment().getDepartmentName().trim()
							.equals("")) {
				if (form.getDepartment().getParentId() != 0L
						&& form.getDepartment().getId() != 0L) {
					if (form.getDepartment().getParentId() == form
							.getDepartment().getId()) {
						errors.rejectValue("department.parentId", "",
								"不能选择自己作为『上级部门』");
					} else {
						d = (Department) this.departmentDao.get(
								Department.class, form.getDepartment()
										.getParentId());
						if (d != null
								&& d.getParentIdStr() != null
								&& d.getParentIdStr().indexOf(
										";" + form.getDepartment().getId()
												+ ";") != -1) {
							errors.rejectValue("department.parentId", "",
									"不能选择自己的下级作为『上级部门』");
						}
					}
				}
			} else {
				errors.rejectValue("department.departmentName", "", "请输入『名称』");
			}
		}

	}

	public DepartmentDao getDepartmentDao() {
		return this.departmentDao;
	}

	public void setDepartmentDao(DepartmentDao departmentDao) {
		this.departmentDao = departmentDao;
	}
}